/**
 * This file is part of the CAKIS project.
 * 
 * Copyright (c) 2009-2010 - Florian Arndt, Christian Kerl
 * 
 * @license GNU Lesser General Public License v3 <http://www.opensource.org/licenses/lgpl-3.0.html>
 * @since   04.05.2010
 * @version SVN: $Id: IpConfigCommand.java 167 2010-05-22 09:40:23Z f.aarndt@web.de $
 */

package org.cakis.client.commands;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.TextField;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;

import org.cakis.client.CakisMIDlet;

/**
 * IpConfigCommand
 * 
 * @author Florian Arndt
 */
public class IpConfigCommand extends AbstractCommand {
	private CakisMIDlet midlet;
	private TextField ipField;

	public IpConfigCommand(CakisMIDlet m, TextField ipField) {
		super("OK", Command.OK, 2);
		midlet = m;
		this.ipField = ipField;
	}

	public void execute() {
		midlet.setIpAddress(ipField.getString());

		try {
			RecordStore ipStore = RecordStore.openRecordStore("ipStore", true);
			RecordEnumeration enums = ipStore
					.enumerateRecords(null, null, true);
			if (!enums.hasNextElement()) {
				ipStore.addRecord(ipField.getString().getBytes(), 0, ipField
						.getString().getBytes().length);
			} else {
				ipStore.setRecord(enums.nextRecordId(), ipField.getString()
						.getBytes(), 0, ipField.getString().getBytes().length);
			}
			System.out.println(new String(enums.nextRecord()).trim());
			ipStore.closeRecordStore();
		} catch (RecordStoreFullException e) {
			e.printStackTrace();
		} catch (RecordStoreNotFoundException e) {
			e.printStackTrace();
		} catch (RecordStoreException e) {
			e.printStackTrace();
		}
		
		midlet.splashDone();
	}

}
